/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import io.jboot.Jboot;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.utils.CookieUtil;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.validate.CaptchaValidate;
import io.jboot.web.validate.EmptyValidate;
import io.jboot.web.validate.Form;
import io.jplus.JplusConsts;
import io.jplus.admin.model.User;
import io.jplus.admin.service.UserService;
import io.jplus.core.web.base.BaseController;
import io.jplus.utils.GsonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;

import java.util.List;
import java.util.Map;
import java.util.Random;

@RequestMapping(value = "/", viewPath = JplusConsts.BASE_VIEW_PATH)
public class LoginController extends BaseController {
    public final Log log = Log.getLog(LoginController.class);

    @RPCInject
    UserService userService;

    public void index() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            redirect("/admin");
        } else {
            render("login.html");
        }
    }


    public void captcha() {
        renderCaptcha();
    }


    @Before(POST.class)
    @EmptyValidate(value = {@Form(name = "username", message = "账号不能为空!"),
            @Form(name = "password", message = "密码不能为空!"), @Form(name = "captcha", message = "验证码不能为空！")})
    @CaptchaValidate(form = "captcha", message = "验证码不正确！")
    public void doLogin(String username, String password) {
        Ret ret;
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false, getIPAddress());
        Subject subject = SecurityUtils.getSubject();
        try {
            //是否需要进行验证
            if (!subject.isAuthenticated()) {
                subject.login(token);
            }
            User user = userService.findByUserName(username);
            CookieUtil.put(this, JplusConsts.JPLUS_USER_ID, user.getId());
            ret = Ret.ok().set(JplusConsts.RET_CODE, 0);

        } catch (AuthenticationException e) {
            ret = Ret.fail(JplusConsts.RET_MSG, "登录认证异常！").set(JplusConsts.RET_CODE, 1);
            log.error(e.getMessage(), e.getCause());
        } catch (Exception ex) {
            ret = Ret.fail(JplusConsts.RET_MSG, "登录认证异常！").set(JplusConsts.RET_CODE, 2);
            log.error(ex.getMessage(), ex.getCause());
        }
        if (isAjaxRequest()) {
            renderJson(ret);
        } else {
            redirect(ret.isOk() ? "/admin" : "/admin/login");
        }

    }

    @RequiresUser
    public void logout() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
        render("login.html");
    }


    /**
     * 登录页面获取BING每日一图
     *
     * @throws Exception
     */
    public void bgImg() {

        String cacheName = "__jplus_login__";

        String images = Jboot.getCache().get(cacheName, "bgImg");
        if (StrUtil.isNotBlank(images)) {
            List<Map<String, Object>> gson = GsonUtil.jsonToListMap(images);
            String image = gson.get(new Random().nextInt(8)).get("url").toString();
            renderJson(Ret.ok("image", image));
            return;
        }

        String imgString = HttpUtils.get("http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8");
        JSONObject json = JSONObject.parseObject(imgString);

        images = json.get("images").toString();
        if (StrUtil.isBlank(images)) {
            renderJson(Ret.fail());
            return;
        }
        Jboot.getCache().put(cacheName,"bgImg",images,3600);
        List<Map<String, Object>> gson = GsonUtil.jsonToListMap(images);
        String image = gson.get(new Random().nextInt(8)).get("url").toString();
        renderJson(Ret.ok("image", image));
    }

}
